var express = require('express');
var router = express.Router();
var user = require('../models/user');
var crypto = require('crypto');

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post('/register', function (req, res, next) {
        if (!req.body.userName) {
            res.json({status: 1, message: '用户名为空'})
        }
        if (!req.body.password) {
            res.json({status: 1, message: '用户密码为空'});
        }
        if (!req.body.userMail) {
            res.json({status: 1, message: '用户邮箱为空'});
        }
        if (!req.body.userPhone) {
            res.json({status: 1, message: '用户手机号为空'});
        }

        user.findByUserName(req.body.userName)
            .then((users) => {
                if (users.length != 0) {
                    res.json({status: 1, message: '用户名已注册'});
                } else {
                    var registerUser = new user({
                        userName: req.body.userName,
                        password: req.body.password,
                        userMail: req.body.userMail,
                        userPhone: req.body.userPhone,
                        userAdmin: 0,
                        userPower: 0,
                        userStop: 0
                    });
                    registerUser.save().then(user => {
                        res.json({status: 0, message: '注册成功'})
                    });
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
)

router.post('/login', function (req, res, next) {
    // 用户名密码都不能为空
    if (!req.body.userName) {
        res.json({status: 1, message: '用户名不能为空'});
    }
    if (!req.body.password) {
        res.json({status: 1, message: '密码不能为空'});
    }
    // 用户名是否存在
    user.findUserLogin(req.body.userName, req.body.password)
        .then((findUsers) => {
            if (findUsers.length != 0) {
                var token_after = getMD5Password(findUsers[0]._id);
                res.json({status: 0, data: {token: token_after, user: findUsers, message: '用户登录成功'}});
            } else {
                res.json({status: 1, message: '用户名或密码错误'})
            }
        })
        .catch((err) => {
            console.log(err);
        });
});

router.post('/forgot-password', (req, res, next) => {
    // 忘记密码,非登录状态下 1. 通过邮件验证修改 2. 通过手机号验证修改
    if (!req.body.user_id) {
        res.json({status: 1, message: '用户名不能为空'});
    }
    if (!req.body.verificationType) {
        res.json({status: 1, message: '验证类型不能为空'});
    }
    user.findById(req.body.user_id)
        .then((findUser) => {
            if (req.body.verificationType == 1) {
                if (findUser.userMail == req.body.mail && req.body.verificationCode == '888888') {
                    user.updateUserPassword(req.body.user_id, req.body.newPassword)
                    res.json({status: 0, message: '修改成功'});
                } else {
                    res.json({status: 1, message: "邮箱用户不匹配，验证码错误！"});
                }
            } else if (req.body.verificationType == 2) {
                if (findUser.userPhone == phone && verificationCode == '888888') {
                    res.json({status: 0, message: '修改成功'});
                } else {
                    res.json({status: 1, message: "手机号用户不匹配，验证码错误！"});
                }
            } else {
                res.status(500).send('somenthing is wrong!');
            }
        })
        .catch(err => {
            console.log(err);
            res.status
        });
})

router.post('/reset-password', (req, res, next) => {
    if (!req.body.userId) {
        res.json({status: 1, message: '用户id为空'});
    }
    if (!req.body.token) {
        res.json({status: 1, message: '用户token为空'});
    }
    user.findById(req.body.userId)
        .then(findUser => {
            if (findUser && req.body.token == getMD5Password(req.body.userId)) {
                user.updateUserPassword(req.body.userId, req.body.newPassword);
                res.json({status: 0, message: '密码修改成功'});
            } else {
                res.json({status: 1, message: '用户不存在，或者用户未登录'});
            }
        })
});

router.post('/findPassword', (req, res, next) => {
    if (req.body.repassword) {
        if (req.body.token) {
            if (!req.body.user_id) {
                res.json({status: 1, message: '用户名不存在'});
            }
            if (!req.body.password) {
                res.json({status: 1, message: '用户密码不存在'});
            }
            if (req.body.token == getMD5Password(req.body.user_id)) {
                user.findOne(req.body.user_id, req.body.password)
                    .then((findUser) => {
                        if (findUser) {
                            user.update(req.body.user_id, req.body.password);
                        }
                    })
                    .catch(

                    );
            }
        }
    }
});

router.get('/queryUser', (req, res, next) => {
    user.findAll()
        .then(data => {
            console.log(data);
            res.json({status: 0, message: "查询成功", 'data': data});
        })
        .catch(err => {
            console.log(err);
        })
});

//用户提交评论
router.post('/commment', function (req, res) {
    if (!req.body.username) {
        var username = "匿名用户"
    }
    if (!req.body.movie_id) {
        res.json({status: 1, message: "电影id为空"})
    }
    if (!req.body.context) {
        res.json({status: 1, message: "评论内容为空"})
    }

    var saveComment = new comment({
        movie_id: req.body.movie_id,
        username: req.body.username ? req.body.username : username,
        context: req.body.context,
        check: 0
    })
    saveComment.save(function (err) {
        if (err) {
            res.json({status: 1, message: err})
        } else {
            res.json({status: 0, message: '评论成功'})
        }

    })
});

function getMD5Password(id) {
    var md5 = crypto.createHash('md5');
    var token_before = id + "sd1f3asd5f4sfa";
    return md5.update(token_before).digest('hex');
}

module.exports = router;
